package com.shundr.shipper.user;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult.AddressComponent;
import com.shundr.shipper.R;
import com.shundr.shipper.base.BaseActivity;
import com.shundr.shipper.common.AgreementActivity;
import com.shundr.shipper.common.util.BaiduMapManager;
import com.shundr.shipper.common.util.DialogUtil;
import com.shundr.shipper.common.util.JsonUtil;
import com.shundr.shipper.common.util.PrefConstants;
import com.shundr.shipper.common.util.PrefUtils;
import com.shundr.shipper.common.util.ProgressDialogHelper;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.common.view.DialogDisplay.OnDisplayListener;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.frame.service.SmsObserver;
import com.shundr.shipper.frame.util.LLogger;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.user.http.UserRequest;
import com.shundr.shipper.user.model.UserInfo;
import com.shundr.shipper.user.util.UserUtil;

public class RegisterActivity extends BaseActivity {
	private EditText etName;
	private EditText etPw;
	private EditText etPwConfirm;
	private EditText etCode;
	
	private Button btnNameClear;
	private Button btnPasswordClear;
	
	private Button btnGetCode;
	private Button btnRegister;
	
	private RadioGroup rgType;
	
	private Timer mTimer;
	private static final int TOTAL = 60;
	private int timerTotal = TOTAL;
	
	private String userType = "1";//0代表司机，1代表货主
	
	private BaiduMapManager mMapManager;
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UserRequest.LOGIN_SUCCESSED:
				try {
					ProgressDialogHelper.dismiss();
					String data = msg.obj.toString();
					JSONObject obj = new JSONObject(data);
					String accessToken = obj.getString("accessToken");
					UserInfo user = JsonUtil.fromJson(obj.getJSONObject("user").toString(), UserInfo.class);
					UserUtil.saveUserToLocal(mContext, user, accessToken);
					PrefUtils.setPrefString(mContext, PrefConstants.GET_WALLET_TIME, "");
					ProgressDialogHelper.dismiss();
					PrefUtils.setPrefString(mContext, PrefConstants.USER_PHONE, etName.getText().toString());
					ToastHelper.toastShort(mContext, "注册成功");
					if (LContext.getUserValidationStatus() == -1) {//未认证
						DialogUtil.noticeAuthDialog(mContext, "认证", "您还未完成认证,认证后可无限制使用所有功能哦，现在去认证吧！", "去认证", "以后再说", new OnDisplayListener() {
							
							@Override
							public void confirm() {
								startActivity(new Intent(mContext, UserInfoActivity.class));
								finish();
							}
							
							@Override
							public void cancel() {
								setResult(501);
								finish();
							}
						});
					}else{
						mHandler.postDelayed(new Runnable() {
							
							@Override
							public void run() {
								setResult(501);
								finish();
							}
						}, 1000);
					}
				} catch (JSONException e) {
					e.printStackTrace();
					ToastHelper.toastShort(mContext, "注册成功");
				}
				break;
			case UserRequest.CHECK_PHONE_SUCCESSED:
				new UserRequest(mContext, mHandler).getAuthCode(etName.getText().toString(), UserInfo.CatpchaType.REGISTER);
				mHandler.sendEmptyMessage(1999);
				break;
			case 1999:
				mTimer = new Timer();
				mTimer.schedule(new TimerTask() {
					
					@Override
					public void run() {
						mHandler.sendEmptyMessage(2000);
					}
				}, 0,1000);
				break;
			case UserRequest.CHECK_CAPTCHA_SUCCESSED:
				//注册
				new UserRequest(mContext, mHandler).register(userType, etName.getText().toString(), etPw.getText().toString(), etCode.getText().toString());
				break;
			case UserRequest.REGISTER_SUCCESSED:
				//注册成功
				new UserRequest(mContext, mHandler).login(etName.getText().toString(), etPw.getText().toString());
				break;
			case 2000:
				if(timerTotal != 0){
					timerTotal = timerTotal - 1;
					btnGetCode.setText(timerTotal + "秒后重新获取");
					btnGetCode.setBackgroundResource(R.drawable.btn_gray_light_selector);
					btnGetCode.setEnabled(false);
				}else{
					timerTotal = TOTAL;
					btnGetCode.setText("点击重新获取");
					btnGetCode.setBackgroundResource(R.drawable.btn_orange_light_selector);
					btnGetCode.setEnabled(true);
					mTimer.cancel();
					mTimer = null;
				}
				break;
			case LHttpRequest.REQUEST_FAILED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(mContext, msg.obj.toString());
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		initView();
		mMapManager = new BaiduMapManager(mContext, null);
		mMapManager.initMap();
		mMapManager.setLocationListener(new MyLocationListenner());
		mMapManager.startLocation();
		initSmsObserver();
	}
	
	private SmsObserver mSmsObserver;
	private void initSmsObserver(){
		mSmsObserver = new SmsObserver(this, new Handler(), etCode);
		// 注册短信变化监听
		getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, mSmsObserver);
	}
	
	private void initView(){
		findViewById(R.id.layout_agreement).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent=new Intent(mContext, AgreementActivity.class);
				startActivity(intent);				
			}
		});
		
		btnNameClear = (Button) findViewById(R.id.btn_name_clear);
		btnNameClear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				etName.setText("");
			}
		});
		etName = (EditText)findViewById(R.id.et_username);
		btnPasswordClear = (Button) findViewById(R.id.btn_password_clear);
		btnPasswordClear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				etPw.setText("");
			}
		});
		etPw = (EditText)findViewById(R.id.et_account);
		etPwConfirm = (EditText)findViewById(R.id.et_account_confirm);
		etCode = (EditText)findViewById(R.id.et_code);
		
		etName.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				LLogger.e("onTextChanged   "+s.toString());
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				LLogger.e("beforeTextChanged   "+s.toString());
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(s.length() > 0){
					btnNameClear.setVisibility(View.VISIBLE);
				}else{
					btnNameClear.setVisibility(View.GONE);
				}
				if(s.length() == 11){
					btnGetCode.setBackgroundResource(R.drawable.btn_orange_light_selector);
					btnGetCode.setEnabled(true);
				}else{
					btnGetCode.setBackgroundResource(R.drawable.btn_gray_light_selector);
					btnGetCode.setEnabled(false);
				}
			}
		});
		
		etPw.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(s.length() > 0){
					btnPasswordClear.setVisibility(View.VISIBLE);
				}else{
					btnPasswordClear.setVisibility(View.GONE);
				}
			}
		});	
//		
		btnGetCode = (Button)findViewById(R.id.btn_get_auth_code);
		btnRegister = (Button)findViewById(R.id.btn_register);
		
		btnGetCode.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(StringUtil.isMobileNO(etName.getText().toString().trim())){
					new UserRequest(mContext, mHandler).checkPhone(etName.getText().toString().trim());
				}else{
					ToastHelper.toastShort(mContext, "手机号码格式不正确");
				}
			}
		});
		
		btnRegister.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(check()){
					ProgressDialogHelper.show(mContext, "正在注册,请稍后...");
					new UserRequest(mContext, mHandler).checkCaptcha(etName.getText().toString().trim(), etCode.getText().toString().trim());
				}
			}
		});
		
		rgType = (RadioGroup)findViewById(R.id.rg_type);
		rgType.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.rb_cargo:
					userType = "1";
					break;
				case R.id.rb_car:
					userType = "0";
					break;

				default:
					break;
				}
			}
		});
	}
	
	private boolean check(){
		if(StringUtil.isNull(etName.getText().toString().trim())){
			ToastHelper.toastShort(mContext, "请输入手机号码");
			etName.setText("");
			return false;
		}
		if(!StringUtil.isMobileNO(etName.getText().toString().trim())){
			ToastHelper.toastShort(mContext, "请输入正确格式的手机号码");
			return false;
		}
		if(StringUtil.isNull(etPw.getText().toString().trim())){
			ToastHelper.toastShort(mContext, "请输入6到16位非空格密码");
			etPw.setText("");
			return false;
		}
		if(etPw.getText().toString().trim().length() < 6){
			ToastHelper.toastShort(mContext, "输入的密码长度太短,请重新输入");
			return false;
		}
		if(etPw.getText().toString().trim().length() > 16){
			ToastHelper.toastShort(mContext, "输入的密码长度太长,请重新输入");
			return false;
		}
		
//		if(!StringUtil.isEqual(etPw.getText().toString(), etPwConfirm.getText().toString())){
//			ToastHelper.toastShort(mContext, "密码不一致,请确认");
//			return false;
//		}
		
		if(StringUtil.isNull(etCode.getText().toString().trim())){
			ToastHelper.toastShort(mContext, "请输入验证码");
			return false;
		}
		return true;
	}
	
	private boolean isFirstLoc = true;// 是否首次定位
	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null)
				return;
			if (isFirstLoc) {
				// isFirstLoc = false;
				// 获取当前位置的经纬度
				LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
				LLogger.e("维度 ： " + location.getLatitude() + "\n" + "经度  : " + location.getLongitude());
				mMapManager.setGeoCoderResultListener(new MyGeoCoderListener());
				mMapManager.reverseLocation(latLng);
			}

		}
		public void onReceivePoi(BDLocation poiLocation) {

		}
	}

	public class MyGeoCoderListener implements OnGetGeoCoderResultListener {

		@Override
		public void onGetGeoCodeResult(GeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				ToastHelper.toastShort(mContext, "定位失败");
			} else {
				ToastHelper.toastShort(mContext, result.getAddress());
			}
		}

		@Override
		public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				ToastHelper.toastShort(mContext, "定位失败");
			} else {
				try {
					AddressComponent component = result.getAddressDetail();
					String mAddress = component.province + component.city
							+ component.district + component.street
							+ component.streetNumber;
					LContext.mAddress = mAddress;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		switch (resultCode) {
		case 501:
			setResult(501);
			finish();
			break;

		default:
			break;
		}
	}
	
	@Override
	public void onPause() {
		mMapManager.stop();
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		getContentResolver().unregisterContentObserver(mSmsObserver);
		mMapManager.destroy();
		super.onDestroy();
	}
	
}
